<template>
  <div class="divSize" style="margin: auto">
    <el-form
      class="elform"
      ref="examRuleFormRef"
      :model="examInfo"
      status-icon
      label-width="80px"
      label-position="right"
      :inline="true"
      :rules="examInfoRules"
    >
      <h1 style="font-size: 26px">笔试安排</h1>
      <br />
      <div>
        <h3 style="color: #909399">请填写卓越班班级名称:</h3>
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="examInfo.className" :disabled="disabled"></el-input>
        </el-form-item>
        <h3 style="color: #909399">请设置笔试时间:</h3>
        <el-form-item
          :rules="[{ required: true, message: '请选择笔试时间', trigger: 'burl' }]"
          label="笔试时间"
        >
          <el-date-picker
            v-model="date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :disabled="examDisable"
            style="width: 300px"
          />
        </el-form-item>
        <br />

        <h4 style="color: #909399">选择每日开始及结束时间:</h4>
        <div style="padding-top: 5px">
          <el-form-item prop="examStartTime" label="开始时间">
            <el-time-select
              :disabled="examDisable"
              v-model="examInfo.examStartTime"
              placeholder="开始时间"
              :max-time="examInfo.examEndTime"
              format="HH:mm:ss"
              start="08:30"
              step="00:10"
              end="21:30"
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item prop="examEndTime" label="结束时间">
            <el-time-select
              :disabled="examDisable"
              v-model="examInfo.examEndTime"
              placeholder="结束时间"
              :min-time="examInfo.examStartTime"
              format="HH:mm:ss"
              start="08:30"
              step="00:10"
              end="21:30"
              style="width: 150px"
            />
          </el-form-item>
        </div>
        <br />
        <el-form-item style="padding-left: 30%">
          <el-button type="warning" @click="editExam()">{{ warningText }}</el-button>
          <span style="margin-left: 100px"></span>
          <el-button :disabled="examDisable" type="primary" @click="examSubmitForm(examRuleFormRef)"
            >提交</el-button
          >
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch, h } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { setExamInfoService, updateTimeInfoService, getTimeInfoService } from '@/apis/timeManage'

const disabled = ref(false)
const date = ref([])
const examInfo = ref({
  timeId: undefined,
  className: '',
  examStartDate: '',
  examEndDate: '',
  examStartTime: '',
  examEndTime: ''
})

const examDisable = ref(true)
const warningText = ref('编辑笔试')

const examRuleFormRef = ref<FormInstance>()
const examInfoRules = reactive<FormRules<typeof examInfo>>({
  className: [{ required: true, message: '请填写卓越班班级名称', trigger: 'burl' }],
  examStartTime: [{ required: true, message: '请选择笔试开始时间', trigger: 'burl' }],
  examEndTime: [{ required: true, message: '请选择笔试结束时间', trigger: 'burl' }]
})

const editExam = () => {
  if (warningText.value === '取消编辑') getTimeInfo()
  examDisable.value = !examDisable.value
  warningText.value === '取消编辑'
    ? (warningText.value = '编辑笔试')
    : (warningText.value = '取消编辑')
}

const disabledFun = () => {
  if (
    examInfo.value.className == '' ||
    (Format(new Date()) > examInfo.value.examEndDate &&
      Format(new Date()) > examInfo.value.exemEndDate &&
      Format(new Date()) > examInfo.value.intvEndDate)
  ) {
    disabled.value = false
  } else {
    disabled.value = true
  }
}
onMounted(() => {
  getTimeInfo()
})

const getTimeInfo = async () => {
  let result = await getTimeInfoService()
  if (result.data.code === 1) {
    if (result.data.data != null && result.data.data != '') {
      examInfo.value = result.data.data
      date.value[0] = examInfo.value.examStartDate
      date.value[1] = examInfo.value.examEndDate
      disabledFun()
    }
  } else {
    ElMessage.error(result.data.msg)
  }
}

const examSubmitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      if (disabled.value === false) {
        ElMessageBox({
          title: '警告',
          message: h('p', null, [
            h('span', null, '卓越班名称设置后本次报名期间将无法更改，确认设置卓越班名称为 '),
            h('strong', { style: 'color: #F56C6C' }, examInfo.value.className),
            h('span', null, ' 吗?')
          ]),
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          showCancelButton: true,
          center: true,
          type: 'warning'
        })
          .then(() => {
            if (examInfo.value.timeId === undefined) {
              setExamInfoService(examInfo.value).then((result) => {
                if (result.data.code === 1) {
                  ElMessage.success('设置考试成功')
                  editExam()
                  disabledFun()
                } else {
                  ElMessage.error(result.data.msg ? result.data.msg : '操作失败')
                }
              })
            } else {
              updateTimeInfoService(examInfo.value).then((result) => {
                if (result.data.code === 1) {
                  disabledFun()
                  editExam()
                  ElMessage.success('更新笔试成功')
                } else {
                  ElMessage.error(result.data.msg ? result.data.msg : '操作失败')
                }
              })
            }
          })
          .catch(() => {})
      } else {
        if (examInfo.value.timeId === undefined) {
          setExamInfoService(examInfo.value).then((result) => {
            if (result.data.code === 1) {
              ElMessage.success('设置考试成功')
              editExam()
              disabledFun()
            } else {
              ElMessage.error(result.data.msg ? result.data.msg : '操作失败')
            }
          })
        } else {
          updateTimeInfoService(examInfo.value).then((result) => {
            if (result.data.code === 1) {
              disabledFun()
              editExam()
              ElMessage.success('更新笔试成功')
            } else {
              ElMessage.error(result.data.msg ? result.data.msg : '操作失败')
            }
          })
        }
      }
    } else {
      ElMessage.error('请正确填写相关信息再提交')
      return false
    }
  })
}

function Format(date: Date) {
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  if (month < 10) month = '0' + month
  if (day < 10) day = '0' + day
  return year + '-' + month + '-' + day
}

watch(date, (newValue: Date[], oldValue: Date[]) => {
  if (newValue && newValue.length == 2) {
    examInfo.value.examStartDate = Format(newValue[0])
    examInfo.value.examEndDate = Format(newValue[1])
  }
})
</script>

<style>
.elform {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
</style>
